//
//  GridView.m
//  Game of Life
//
//  Created by James Durkee on 5/12/09.
//  Copyright 2009 James and MP. All rights reserved.
//

#import "GridView.h"


@implementation GridView
- (Grid *)grid {
	return grid;
}

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        grid = [[Grid alloc] initWithRows:50 Cols:50];
    }
    return self;
}

- (void)awakeFromNib {
	NSLog(@"%@ awokeFromNib", [self className]);
}

- (void)drawRect:(NSRect)rect {
	[[NSColor blackColor] set];
	NSBezierPath *background = [NSBezierPath bezierPathWithRect:rect];
	[background fill];
	
	[[NSColor grayColor] set];
	
	height = rect.size.height;
	width = rect.size.width;
	
	//NSLog(@"Height: %f Width: %f", height, width);
	
    cellHeight = height / (float)[grid rows];
	cellWidth = width / (float)[grid columns];
	
	NSEnumerator *colEnumerator = [grid columnEnumerator];
	id c;
	while (c = [colEnumerator nextObject]) {
		NSEnumerator *cellEnumerator = [c objectEnumerator];
		id cell;
		while (cell = [cellEnumerator nextObject]) {
			NSPoint origin = NSMakePoint((float)[cell row] * cellWidth, (float)[cell col] * cellHeight);
			NSSize size = NSMakeSize(cellWidth, cellHeight);
			NSRect cellRect = NSMakeRect(origin.x, origin.y, size.width - 2, size.height - 2);
			NSBezierPath *cellPath = [NSBezierPath bezierPathWithOvalInRect:cellRect];
			
			[cell setBounds:cellRect];
			
			[cellPath stroke];
			
			if ([cell isAlive]) {
				[[NSColor greenColor] set];
				[cellPath fill];
				[[NSColor grayColor] set];
			}
		}
	}
}

- (void)mouseDown:(NSEvent *)event {
	NSPoint location = [self convertPointFromBase:[event locationInWindow]];
	
	int r = (int) (location.x/(width/[grid columns]));
	int c = (int) (location.y/(height/[grid rows]));
	
	id cell = [grid cellAtRow:r Col:c];
	
	if ([cell isAlive]) {
		[cell setAlive:NO];
		[cell setNextState:NO];
	} else {
		[cell setAlive:YES];
	}
	
	//[cell toggleAlive];
	[self setNeedsDisplay:YES];
}

- (void)mouseDragged:(NSEvent *)event {
	NSPoint location = [self convertPointFromBase:[event locationInWindow]];
	
	int r = (int) (location.x/(width/[grid columns]));
	int c = (int) (location.y/(height/[grid rows]));
	
	id cell = [grid cellAtRow:r Col:c];
	
	[cell setAlive:YES];
	[self setNeedsDisplay:YES];
}

- (void)rightMouseDragged:(NSEvent *)event {
	NSPoint location = [self convertPointFromBase:[event locationInWindow]];
	
	int r = (int) (location.x/(width/[grid columns]));
	int c = (int) (location.y/(height/[grid rows]));
	
	id cell = [grid cellAtRow:r Col:c];
	
	[cell setAlive:NO];
	[self setNeedsDisplay:YES];
}


- (BOOL)isFlipped {
	return YES;
}

- (void)clear {
	[grid clear];
	[self setNeedsDisplay:YES];
}

- (int)generation {
	return [grid generation];
}

@end